package com.example.car.mapper;

import com.example.car.entity.Order;
import com.example.car.vo.TimeConditionVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class OrderMapper {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Order> list(String userId, int page, int limit) {
        List<Order> orders = mongoTemplate.find(Query.query(Criteria.where("user_id").is(userId)).skip(page - 1).limit(limit), Order.class);

        return orders;
    }

    public boolean addOrder(Order order) {
        order.setStatus(1);
        mongoTemplate.save(order, "order");
        return true;
    }

    public boolean payOrder(String orderId) {

        Order order = mongoTemplate.findOne(new Query(Criteria.where("_id").is(orderId)), Order.class);
        if(order == null) {
            // todo 异常
        }
        order.setStatus(0);
        Update update = new Update();
        update.set("status", 0);

        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(orderId)), update, Order.class);
        return true;
    }


    public Double orderStatistics(TimeConditionVo timeConditionVo) {

        Criteria criteria = new Criteria();

        String startTime = timeConditionVo.getStartTime();
        String endTime = timeConditionVo.getEndTime();

        int judge = 0;

        if(!StringUtils.isBlank(startTime)) {
            criteria.where("startTime").gte(startTime);
            judge++;
        }
        if(!StringUtils.isBlank(startTime)) {
            if(judge == 1) {
                criteria.and("endTime").lte(endTime);
            }else {
                criteria.where("endTime").gte(startTime);
            }
        }
        if(judge == 0) {
            criteria.where("startTime").is(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        }
        List<Order> orders = mongoTemplate.find(Query.query(criteria), Order.class);

        double money = 0;
        for (int i = 0; i < orders.size(); i++) {
            money += orders.get(i).getPrice();
        }
        return money;
    }

    public Long getTotal(String userId) {
        return mongoTemplate.count(Query.query(Criteria.where("customerId").is(userId)), Order.class);
    }
}
